package parse

import (
	"fmt"
	"strconv"
	"strings"
)

// eg13.4, 输入的字符串解析成整数切片

type ParseError struct {
	Index int
	Word  string
	Err   error
}

func (p *ParseError) String() string {
	return fmt.Sprintf("pkg parse: error parsing %s as int", p.Word)
}

func Parse(input string) (numbers []int, err error) {
	defer func() {
		if e := recover(); e != nil {
			// err已经声明过
			// 单独再声明bool值ok
			var ok bool
			err, ok = e.(error)
			if !ok {
				err = fmt.Errorf("pkg: %v", e)
			}
		}

	}()

	fields := strings.Fields(input)
	numbers = fields2numbers(fields)
	return
}

func fields2numbers(fields []string) (numbers []int) {
	if len(fields) == 0 {
		panic("no words to parse")
	}

	for ix, field := range fields {
		num, err := strconv.Atoi(field)
		if err != nil {
			panic(&ParseError{ix, field, err})
		}
		numbers = append(numbers, num)
	}
	return
}
